package com.tsy.server.component.security;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.tsy.server.system.entity.User;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Collections;

/**
 * 自定义用户详情
 *
 * @JsonIgnoreProperties 用于忽略类级别的未知字段。
 * @JsonIgnore 用于忽略类中特定属性或方法的序列化和反序列化。
 */
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class CustomUserDetails implements UserDetails {

    public CustomUserDetails() {
        // 无参构造函数，用于Redis反序列化
        this.user = null;
        this.roleKey = null;
        this.workspaceId = null;
    }

    private static final long serialVersionUID = 1L;
    // 委托 User 实体的方法
    private User user; // 假设这是你的用户实体类
    private String roleKey;
    private String workspaceId;

    public CustomUserDetails(User user, String roleKey, String workspaceId) {
        this.user = user;
        this.roleKey = roleKey;
        this.workspaceId = workspaceId;
    }

    // 实现 UserDetails 接口的方法
    @Override
    public String getUsername() {
        assert user != null;
        return user.getUsername();
    }

    @Override
    public String getPassword() {
        assert user != null;
        return user.getPassword();
    }

    @JsonIgnore
    @Override
    public Collection<GrantedAuthority> getAuthorities() {
        return Collections.singletonList(new SimpleGrantedAuthority(roleKey));
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}